
import { Avatar, message } from 'antd'
import { connect } from 'react-redux';
import { withRouter } from 'react-router';

import {
    header_right,
    header_user,
    header_avator_wrapper,
    header_name,
    login_btn,
    logout_btn,
} from './index.module.css'
import { changeCurrentRoom, changeLog, changeUserInfo } from '../../../store/actions'
import { getUserLogout } from '../../../assets/js/api'
import { imgUrlDev, removeToken } from '../../../assets/js/tools'
import { Link } from 'react-router-dom';
import { exitSocket, getSocket } from '../../../socketEvent';


function HeaderRight(props) {

    const { islogin, user } = props;
    const { changeLog, changeUserInfo, changeCurrentRoom } = props;
    const { history } = props;

    function toLogout() {
        // 退出登录
        getUserLogout({user_id:user.id})
        .then(res => {
            const { code, message: content } = res.data;
            if (code === 1) {
                // 要将跳转放前面,不然当log状态或userInfo改变后会导致routerGuard更新再次进入room页
                exitSocket();
                history.push({pathname: '/home'});
                changeUserInfo();
                changeLog(false);
                changeCurrentRoom();
                removeToken('token');
                message.success({content, duration: 2});
            } else {
                message.error(content);
            }
        })
        .catch(err => {
            console.log(err);
            message.error('一个意外的错误,请稍后重试');
        });
    }

    return (
        <div className={header_right}>
            {
                islogin ? 
                <div className={header_avator_wrapper}>
                    <Link className={header_user} to={{pathname: '/info'}} target="_blank">
                        <Avatar src={imgUrlDev(user.avator)} alt={user.name} />
                        <span className={header_name}>{user.name}</span>
                    </Link>
                    <a className={logout_btn} onClick={toLogout}>退出</a>
                </div> :
                <Link className={login_btn} to={{pathname: '/home', state: {log: true}}}>登录</Link>
            }
        </div>
    )
}


function mapStateToProps(state) {
    return {
        islogin: state.islogin,
        user: state.user,
    }
}
export default connect(
    mapStateToProps,
    {
        changeLog,
        changeUserInfo,
        changeCurrentRoom,
    }
)(withRouter(HeaderRight));